package cn.seqdata.rpt.simple.query;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Objects;

import org.springframework.jdbc.core.RowCountCallbackHandler;

import cn.seqdata.rpt.simple.DynaTable;
import cn.seqdata.rpt.simple.OrderedName;

/** 适用于在一张宽表中抽取维度信息，减少数据传输工作量 */
public class DynaTableCallbackHandler extends RowCountCallbackHandler {
	private final DynaTable pivot;
	// 简单维度，如date, time ...
	private final String[] dimensions;
	// 引用维度，如plant, cgroup ...引用维度必须有三个字段，其后缀分别是_id, _name, _order
	private final String[] refDimensions;
	// 量测数据，如value, qtty, count(*), sum(*)
	private final String[] measures;

	public DynaTableCallbackHandler(DynaTable pivot, String[] dimensions, String[] refDimensions, String[] measures) {
		this.pivot = pivot;
		this.dimensions = dimensions;
		this.refDimensions = refDimensions;
		this.measures = measures;
	}

	@Override
	protected void processRow(ResultSet rs, int rowNum) throws SQLException {
		for (String refDimension : refDimensions) {
			String key = refDimension + "_id";
			Object value = rs.getObject(key);

			Map<Object, OrderedName> rows = pivot.dims.row(refDimension);
			if (Objects.isNull(rows) || !rows.containsKey(value)) {
				OrderedName row = new OrderedName();
				rows.put(value, row);

				row.name = rs.getString(refDimension + "_name");
				Object order = rs.getObject(refDimension + "_order");
				if (order instanceof Number) {
					row.orderNo = ((Number) order).intValue();
				}
			}

			if (Objects.nonNull(value)) {
				pivot.cells.put(rowNum, refDimension, value);
			}
		}

		for (String dimension : dimensions) {
			Object value = rs.getObject(dimension);
			if (Objects.nonNull(value)) {
				pivot.cells.put(rowNum, dimension, value);
			}
		}

		for (String measure : measures) {
			Object value = rs.getObject(measure);
			if (Objects.nonNull(value)) {
				pivot.cells.put(rowNum, measure, value);
			}
		}
	}
}
